from dataclasses import dataclass
from typing import Optional, Dict, Any
from datetime import datetime

@dataclass(frozen=True)
class BaseMessage:
    """基础消息模型（对应服务端ws_server.h的消息结构）"""
#    msgType: str  # 消息类型（参考XWebTrd.c定义）
    pass

@dataclass(frozen=True)
class ConnectedMessage(BaseMessage):
    """连接建立消息"""
    timestamp: datetime

@dataclass(frozen=True)
class DisconnectedMessage(BaseMessage):
    """连接断开消息"""
    reason: str
    code: int

@dataclass(frozen=True)
class TradeMessage(BaseMessage):
    """交易回报消息（对应XWebTrd.c的回报结构）"""
    order_id: str
    symbol: str
    price: float
    quantity: int
    status: str  # NEW, FILLED, CANCELED等

@dataclass(frozen=True)
class MarketMessage(BaseMessage):
    """行情数据消息（对应XWebSnap.c的快照结构）"""
    def __init__(self, **kwargs):
        # 自动设置所有字段
        self.__dict__.update(kwargs)

    def __repr__(self):
        return f"<MarketMessage {self.__dict__}>"

    def __getattr__(self, name):
        """安全访问不存在的属性"""
        try:
            return self.__dict__[name]
        except KeyError:
            return None

@dataclass(frozen=True)
class OrderRequest:
    """订单请求模型（对应XFront.c的订单结构）"""
    userId: str
    frontId: int
    market: int
    securityId: str
    bsType: int
    ordPrice: int
    ordQty: int
    ordType: int

@dataclass(frozen=True)
class OrderResponse:
    """订单响应模型"""
    userId: str
    frontId: int
    market: int
    securityId: str
    bsType: int
    ordPrice: int
    ordQty: int
    ordType: int
    orderid: int
    status: int
    updateTime: int
    errorId: int
    plotid: int
    
@dataclass(frozen=True)
class ConnectionState:
    """连接状态模型（对应ws_server.h的Ws_Client状态）"""
    is_connected: bool
    last_active: datetime
    message_count: int
    client_type: str  # TRADE/MARKET 